package com.training.java.redbox;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.training.java.redbox.domain.Customer;
import com.training.java.redbox.domain.CustomerDAO;
import com.training.java.redbox.domain.CustomerDaoJdbcImpl;
import com.training.java.redbox.domain.DAOException;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	
    	RequestDispatcher rd = request
				.getRequestDispatcher("/WEB-INF/LogIn.jsp");
		rd.forward(request, response);
    	
    }
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		CustomerDAO  customerDao = new CustomerDaoJdbcImpl();
		String username= request.getParameter("username");
		String password= request.getParameter("password");
		
	
		try {
			Customer customer=	customerDao.login(username, password);
			
			RequestDispatcher rd = null;
			
			if(customer == null)
			{
				request.setAttribute("username", username);
				request.setAttribute("ErrorMessage", "Please correct the following errors and try again: The username or password is incorrect.");

				rd= request.getRequestDispatcher("/WEB-INF/LogIn.jsp");
			} else
			{
				HttpSession session = request.getSession();
				session.setAttribute("Customer", customer);
				
				System.out.println("customerid= " + customer.getCustomerId());
				
				rd= request.getRequestDispatcher("/");
			}
			
			rd.forward(request, response);
			
		} catch (DAOException e) {
			e.printStackTrace();
		}
		
		
	

	}

}
